package com.jn.news.ui;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.jn.news.R;
import com.jn.news.utils.Constant;
import com.jn.news.utils.DatabaseHelper;
import com.jn.news.utils.SPUtils;
import com.jn.news.utils.StatusBarUtils;


/**
 * 个人中心
 */
public class PersonalInfoActivity extends AppCompatActivity {

    private TextView tvUsername;
    private TextView tvPhone;
    private TextView tvEmail;
    private TextView tvQQ;
    private RelativeLayout rlLeft;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtils.with(this).init3(2, 102);
        setContentView(R.layout.activity_personal_info);
        initView();
        initData();
    }

    private void initView() {
        rlLeft = findViewById(R.id.rl_left);
        tvUsername = findViewById(R.id.tv_username);
        tvPhone = findViewById(R.id.tv_phone);
        tvEmail = findViewById(R.id.tv_email);
        tvQQ = findViewById(R.id.tv_qq);
    }

    private void initData() {
        rlLeft.setOnClickListener(v -> finish());
        getUserById((int) SPUtils.get(this, Constant.USERID, 0));
    }

    // 根据 id 查询用户信息
    public void getUserById(int id) {
        //初始化创建表
        SQLiteOpenHelper dbHelper = new DatabaseHelper(this);
        // 调用getReadableDatabase()或getWritableDatabase()才算真正创建或打开数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query(
                "user",               // 表名
                new String[]{"id", "name", "password", "phone", "email", "qq"}, // 要查询的字段
                "id=?",               // WHERE 条件
                new String[]{String.valueOf(id)}, // WHERE 参数
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
            String password = cursor.getString(cursor.getColumnIndexOrThrow("password"));
            String phone = cursor.getString(cursor.getColumnIndexOrThrow("phone"));
            String email = cursor.getString(cursor.getColumnIndexOrThrow("email"));
            String qq = cursor.getString(cursor.getColumnIndexOrThrow("qq"));
            tvUsername.setText(name);
            tvPhone.setText(phone);
            tvEmail.setText(email);
            tvQQ.setText(qq);
            cursor.close();

        }

        if (cursor != null) {
            cursor.close();
        }

    }
}